package com.example.demo;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

public class XstreamUtil {

	//xstream扫描路径，根据具体包名指定
	public static final String XSTREAM_SCAN_PACK = "com\\.example\\.(.)*";


	/**
	 * xml文件序列化对象
	 * @param input
	 * @param clazz
	 * @return
	 */
	public static <T> T convertToObject(InputStream input, Class<T> clazz) {
		XStream xstream = new XStream(new DomDriver());
		XStream.setupDefaultSecurity(xstream);
		String[] regex = new String[]{XSTREAM_SCAN_PACK};
		xstream.allowTypesByRegExp(regex);
		xstream.autodetectAnnotations(true);
		xstream.setMode(XStream.NO_REFERENCES);
		xstream.processAnnotations(clazz);
		xstream.setClassLoader(clazz.getClassLoader());
		InputStreamReader reader = new InputStreamReader(input, Charset.forName("UTF-8"));
		T obj = (T) xstream.fromXML(reader);
		return obj;
	}

	/**
	 * 对象转xml
	 * @param obj
	 * @return
	 */
	public static <T> String convertToXml(Object obj) {
		XStream xstream = new XStream(new DomDriver());
		xstream.autodetectAnnotations(true);
		xstream.setMode(XStream.NO_REFERENCES);
		xstream.processAnnotations(obj.getClass());
		xstream.setClassLoader(obj.getClass().getClassLoader());
		return xstream.toXML(obj);
	}
}
